<script setup>
import shopsApi from '@/api/shops';
import { ref, onActivated, onDeactivated } from 'vue';

const loadingData = ref(false);
const authorisedShops = ref([]);

onActivated(() => {
  // 调用时机为首次挂载
  // 以及每次从缓存中被重新插入时
  console.log('onActivated');
  getAuthorisedShops();
});

const getAuthorisedShops = async () => {
  loadingData.value = true;
  try {
    authorisedShops.value = await shopsApi.getAuthorisedShops();
  } catch (error) {
    console.error(error);
  } finally {
    loadingData.value = false;
  }
};
onDeactivated(() => {
   // 在从 DOM 上移除、进入缓存
  // 以及组件卸载时调用
  console.log('onDeactivated');
  reset(); // 重置数据
});

const reset = () => {
  authorisedShops.value = [];
  loadingData.value = false; // 重置加载状态
};
const authTiktokShop = () => {
  // 生产环境app授权地址
  open('https://services.tiktokshop.com/open/authorize?service_id=7442191930300204856&state=publish');
  // 测试环境app授权地址
  // open('https://services.tiktokshop.com/open/authorize?service_id=7421174646379202310');
  // 开发环境app授权地址
  // open('https://services.tiktokshop.com/open/authorize?service_id=7382275735060924165&state=dev');
};
</script>

<template>
  <div class="tiktok-auth-page">
    <el-button @click.stop="authTiktokShop">添加授权</el-button>
    <el-table :data="authorisedShops" v-loading="loadingData" height="78vh">
      <el-table-column label="店铺ID" prop="shopId" width="200"></el-table-column>
      <el-table-column label="店铺名称" prop="shopName" width="200"></el-table-column>
      <el-table-column label="店铺区域" prop="shopRegion" width="100"></el-table-column>
      <el-table-column label="店铺类型" width="100">
        <template #default="{ row }">
          {{ row.shopType === 'CROSS_BORDER' ? '跨境' : '本土'}}
        </template>
      </el-table-column>
      <el-table-column label="授权时间" prop="authorizationTime" min-width="150">
        <template #default="{ row }">
          {{ $utils.datetime.timestampInMillisToDateTime(row.authorizationTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="">
        <template #default>
          <el-button type="text" @click.stop="authTiktokShop">重新授权</el-button>
          <el-button type="text" @click.stop="">解除授权</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped>

</style>
